package com.yjzx.care;

import com.yjzx.care.base.BaseLoop;
import com.yjzx.care.base.Constant;
import com.yjzx.care.base.LoopBuilder;

import java.util.function.BooleanSupplier;
import java.util.function.Consumer;

/**
 * @author yjzx
 * @date 2023/12/28
 * @description do while循环
 */
public final class LoopDoWhile extends BaseLoop {
    public static class LoopDoWhileBuilder implements LoopBuilder {
        private BooleanSupplier judge;
        private Consumer<LoopDoWhile> loopBody;
        protected LoopDoWhileBuilder() {
        }

        public LoopDoWhileBuilder set(BooleanSupplier judge, Consumer<LoopDoWhile> loopBody) {
            this.judge = judge;
            this.loopBody = loopBody;
            return this;
        }
        public LoopDoWhile setAndBuild(BooleanSupplier judge, Consumer<LoopDoWhile> loopBody) {
            this.judge = judge;
            this.loopBody = loopBody;
            return build();
        }
        /**
         * 条件判断输入
         * @param judge 条件判断
         * @return
         */
        public LoopDoWhileBuilder withJudge(BooleanSupplier judge) {
            this.judge = judge;
            return this;
        }
        /**
         * 循环体
         * @param loopBody 循环体
         * @return
         */
        public LoopDoWhileBuilder withLoopBody(Consumer<LoopDoWhile> loopBody) {
            this.loopBody = loopBody;
            return this;
        }

        @Override
        public LoopDoWhile build() {
            if (this.judge==null) {
                this.judge = Constant.JUDGE_TO_TRUE;
            }
            if (this.loopBody==null) {
                return new LoopDoWhile(judge,Constant.loopBody());
            }
            return new LoopDoWhile(judge,loopBody);
        }
    }
    LoopDoWhile(){

    }
    LoopDoWhile(BooleanSupplier judge, Consumer<LoopDoWhile> loopBody) {
        loopBody0(judge, loopBody);
    }

    public LoopDoWhile loopBody(BooleanSupplier judge, Consumer<LoopDoWhile> loopBody) {
        loopBody0(judge, loopBody);
        return this;
    }

    private void loopBody0(BooleanSupplier judge, Consumer<LoopDoWhile> loopBody) {
        this.isLoop();
        do {
            loopBody.accept(this);
        } while (this.isBreak() && judge.getAsBoolean());
        this.toBreak();
    }
}
